package com.lyx.crm;

import com.alibaba.fastjson.JSON;
import com.lyx.crm.base.ResultInfo;
import com.lyx.crm.exceptions.AuthException;
import com.lyx.crm.exceptions.NoLoginException;
import com.lyx.crm.exceptions.ParamsException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Package: com.lyx.crm
 * @ClassName: GlobalExceptionResolver
 * @Author: lyx
 * @CreateTime: 2021/7/18 20:06
 * @Description: 全局异常统一处理
 */
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {
    /**
     * 异常处理方法
     * 返回JSON  （ResponseBody注解就是返回json数据）
     * 返回视图
     *
     * @param request
     * @param response
     * @param handler  方法兑现
     * @param ex       异常对象
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        /**
         * 判断是否抛出未登录异常
         */
        if (ex instanceof NoLoginException) {
            //跳转到登录页面
            ModelAndView mv = new ModelAndView("redirect:/index");
            return mv;
        }

        /**
         * 设置默认返回视图
         */
        ModelAndView modelAndView = new ModelAndView("error");
        //设置异常信息
        modelAndView.addObject("code", 500);
        modelAndView.addObject("msg", "异常，请重试...");

        //判断HandlerMethod
        if (handler instanceof HandlerMethod) {
            //类型转换
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            //获取方法上的responseBody注解对象
            ResponseBody responseBody = handlerMethod.getMethod().getDeclaredAnnotation(ResponseBody.class);

            if (null == responseBody) {
                /**
                 * 返回视图
                 */
                if (ex instanceof ParamsException) {
                    ParamsException p = (ParamsException) ex;
                    modelAndView.addObject("code", p.getCode());
                    modelAndView.addObject("msg", p.getMsg());
                } else if (ex instanceof AuthException) {
                    AuthException p = (AuthException) ex;
                    modelAndView.addObject("code", p.getCode());
                    modelAndView.addObject("msg", p.getMsg());
                }
                return modelAndView;
            } else {
                /**
                 * 返回数据
                 */
                //设置默认的异常处理
                ResultInfo resultInfo = new ResultInfo();
                resultInfo.setMsg("异常异常，请重试！");
                resultInfo.setCode(500);

                //判断自定义异常
                if (ex instanceof ParamsException) {
                    ParamsException p = (ParamsException) ex;
                    resultInfo.setCode(p.getCode());
                    resultInfo.setMsg(p.getMsg());
                }else if (ex instanceof AuthException) {
                    AuthException p = (AuthException) ex;
                    resultInfo.setCode(p.getCode());
                    resultInfo.setMsg(p.getMsg());
                }

                response.setContentType("application/json;charset=UTF-8");
                PrintWriter out = null;
                try {
                    out = response.getWriter();
                    String json = JSON.toJSONString(resultInfo);
                    out.write(json);

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (null != out) {
                        out.close();
                    }
                }
                return null;
            }
        }
        return modelAndView;
    }
}
